package com.lyn.pluginbazaar.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
           NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {

           Bootstrap bootstrap = new Bootstrap()
                   .group(workerGroup)
                   .channel(NioSocketChannel.class)
                   .handler(new ChannelInitializer<SocketChannel>() {
                       @Override
                       protected void initChannel(SocketChannel socketChannel) throws Exception {
                           socketChannel.pipeline().addLast(new NettyClientHandler());
                       }
                   });
           System.out.println("客户端准备好了");

           ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",6668).sync();

           channelFuture.channel().closeFuture().sync();
       }finally {
           workerGroup.shutdownGracefully();
       }


    }

    private static class NettyClientHandler extends ChannelInboundHandlerAdapter{

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            System.out.println("client"+ctx);
            ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server",Charset.defaultCharset()));
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf= (ByteBuf) msg;
            System.out.println("服务器发送得消息："+buf.toString(Charset.defaultCharset()));
            System.out.println("服务器地址："+ctx.channel().remoteAddress());
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.close();
        }
    }
}
